package com.sinaapp.gavinzhang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by gavin on 15-7-26.
 */
public class Zhihu {
    public static void main(String[] args)
    {
        try {
            //Document html = Jsoup.connect("http://www.zhihu.com/people/chi-zi-you").get();
            //Elements avatar = html.select(".zm-profile-side-topics").select(".avatar");
            /*for (Element e : avatar)
            {
                System.out.println(e.attr("title"));
            }*/


            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

            HttpGet get = new HttpGet("http://www.zhihu.com/people/chi-zi-you");



            CloseableHttpResponse response = httpClient.execute(get);
            setCookie(response);
            String responseHtml = EntityUtils.toString(response.getEntity());

            //printResponse(response);
            //System.out.println(responseHtml);
            //System.exit(0);
            String xsrfValue = responseHtml.split("<input type=\"hidden\" name=\"_xsrf\" value=\"")[1].split("\"/>")[0];
            System.out.println("xsrfValue:" + xsrfValue);
            response.close();
            //System.exit(-1);
            List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
            valuePairs.add(new BasicNameValuePair("_xsrf", xsrfValue));
            valuePairs.add(new BasicNameValuePair("start",""+(System.currentTimeMillis()/1000)));
            //valuePairs.add(new BasicNameValuePair("email", "714728157@qq.com"));
            //valuePairs.add(new BasicNameValuePair("password", "xxxx"));
            //valuePairs.add(new BasicNameValuePair("remember_me", "true"));
            //valuePairs.add(new BasicNameValuePair("captcha", "true"));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
            HttpPost post = new HttpPost("http://www.zhihu.com/people/chi-zi-you/activities");
            //post.setHeader("Host","www.zhihu.com");
            //post.setHeader("User-Agent","Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:1.9.3.2) Gecko/20100803");
            //post.setHeader("Accept","*/*");
           /* post.setHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            post.setHeader("Accept-Encoding","gzip,deflate");
            post.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            post.setHeader("X-Requested-With","XMLHttpRequest");
            post.setHeader("Referer", "http://www.zhihu.com");*/
            //post.setHeader("Cookie", " cap_id=\"YjA5MjE0YzYyNGQ2NDY5NWJhMmFhN2YyY2EwODIwZjQ=|1437610072|e7cc307c0d2fe2ee84fd3ceb7f83d298156e37e0\"; ");

            post.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(post);//登录
            HttpEntity entity1 = post.getEntity();
            //String s = new String(entity.getContent());
            byte[] bs = new byte[1024];

            //printResponse(httpResponse);

            JSONObject jo = JSON.parseObject(EntityUtils.toString(httpResponse.getEntity()));
            JSONArray ja = jo.getJSONArray("msg");
            Document activaty = Jsoup.parse(ja.get(1).toString());
            Elements question = activaty.select(".question_link");
            for (Element e : question)
            {
                System.out.println(e.text());
            }
            Elements topic = activaty.select(".topic-link");
            for (Element e : topic)
            {
                System.out.println(e.text());
            }
            System.exit(-3);
            ByteArrayBuffer bab = new ByteArrayBuffer(entity1.getContent().available());
            System.out.println(entity1.getContent().read(bs, 0, bs.length));
            bab.append(bs, 0, bs.length);

            while (entity1.getContent().read(bs,0,bs.length) != 0)
            {
                bab.append(bs,0,bs.length);
            }

            System.out.println(new String(bab.toByteArray()));
            //printResponse(httpResponse);
            System.exit(-2);
            HttpGet g = new HttpGet("http://www.zhihu.com/question/following");
            String c = setCookie(httpResponse);
            g.setHeader("Cookie",c);
            CloseableHttpResponse r = httpClient.execute(g);//获取子集关注的问题页面测试一下是否登陆成功
            String content = EntityUtils.toString(r.getEntity());
            System.out.println(content);
            r.close();
            httpClient.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map<String,String> cookieMap = new HashMap<String, String>(64);
    public static String setCookie(HttpResponse httpResponse)
    {
        System.out.println("----setCookieStore");
        Header headers[] = httpResponse.getHeaders("Set-Cookie");
        if (headers == null || headers.length==0)
        {
            System.out.println("----there are no cookies");
            return null;
        }
        //System.out.println(headers[0].getValue());
        String cookie = "";
        for (int i = 0; i < headers.length; i++) {
            cookie += headers[i].getValue();
            if(i != headers.length-1)
            {
                cookie += ";";
            }
            //System.out.println(headers[i].getValue());
        }

        String cookies[] = cookie.split(";");
        //System.out.println(cookies.length+"       "+cookies[0]);
        for (String c : cookies)
        {
            c = c.trim();
            if(cookieMap.containsKey(c.split("=")[0]))
            {
                cookieMap.remove(c.split("=")[0]);
            }
            cookieMap.put(c.split("=")[0], c.split("=").length == 1 ? "":(c.split("=").length ==2?c.split("=")[1]:c.split("=",2)[1]));
            //System.out.println(c.split("=")[0]+" value: "+ (c.split("=").length == 2 ? c.split("=")[1]:""));
        }
        System.out.println("----setCookieStore success");
        String cookiesTmp = "";
        for (String key :cookieMap.keySet())
        {
            cookiesTmp +=key+"="+cookieMap.get(key)+";";
        }

        //System.out.println(cookieMap.size()+" "+cookies.length+" "+cookiesTmp);
        return cookiesTmp.substring(0,cookiesTmp.length()-2);
    }

    public static void printResponse(HttpResponse httpResponse)
            throws ParseException, IOException {
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 响应状态
        System.out.println("status:" + httpResponse.getStatusLine());
        System.out.println("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext()) {
            System.out.println("\t" + iterator.next());
        }
        // 判断响应实体是否为空
        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            System.out.println("response length:" + responseString.length());
            System.out.println("response content:"
                    + responseString.replace("\r\n", ""));
        }
    }
}
